import { useRef, useState, useEffect, RefObject } from 'react'
import style from './tabBar.module.less'
import { WindowSchema } from '@src/components/schema/window';
import { useSelector, useDispatch } from 'react-redux';
import { INIT_TAB_STATE } from '@redux/reducers/tab';
import { CloseOutlined, DownOutlined, HomeFilled } from '@ant-design/icons'
import { delWindow, setActiveWindowId } from '@redux/actions/tab';
import { Popover } from 'antd'
import classNames from 'classnames';

/**
 * 隐藏菜单内是否包含当前展示菜单
 */
function IsHasCurrentPage (list: WindowSchema[], activeWindowId: string) {
  return list.some(tab => tab.id === activeWindowId)
}

function initShowAndHideList (ref: HTMLDivElement,windows: WindowSchema[],setShowTabList: (v: WindowSchema[]) => void, setHideTabList: (v: WindowSchema[]) => void) {
  const list = windows.map(page => {
    const width = page.width || 0
    if (!page.closable) {
      return width + 24
    }
    return width + 48
  })
  const maxWidth = ref.offsetWidth - 48
  let num = 0
  const showTabList: WindowSchema[] = []
  const hideTabList: WindowSchema[] = []
  list.forEach((li, i) => {
    if (num + li <= maxWidth) {
      num += li
      showTabList.push(windows[i])
    } else {
      hideTabList.push(windows[i])
    }
  })
  setShowTabList(showTabList)
  setHideTabList(hideTabList)
}

function Main () {
  const content = useRef<HTMLDivElement>(null)
  const [showTabList, setShowTabList] = useState<WindowSchema[]>([])
  const [hideTabList, setHideTabList] = useState<WindowSchema[]>([])
  const [visible, setVisible] = useState(false)
  const dispatch = useDispatch()
  const { windows, activeWindowId } = useSelector((state: { tab: INIT_TAB_STATE }) => {
    return {
      windows: state.tab.windows,
      activeWindowId: state.tab.activeWindowId
    }
  })
  useEffect(() => {
    if (content.current !== null) {
      initShowAndHideList(content.current, windows, setShowTabList, setHideTabList)
    }
  }, [content, windows])
  const otherContent = (
    <div className={style['hide-tabs']}>
      <ul>
        {hideTabList.map(item => {
          const className = item.id === activeWindowId ? style.active : ''
          return (
            <li key={item.id} className={className} onClick={() => dispatch(setActiveWindowId(item.id))}>
              <div className={style['hide-tab__title']}>{item.title}</div>
              <div className={style['hide-tab__close-btn']}>
                <CloseOutlined className={style['hide-table__close-btn__icon']} onClick={(e) => { 
                  e.stopPropagation()
                  dispatch(delWindow(item.id))
                }} />
              </div>
            </li>
          )
        })}
      </ul>
    </div>
  )
  return (
    <div className={style['tab-bar']} ref={content}>
      {
        showTabList.map(item => {
          let className = `${style['tab-bar__tab']}`
          if (item.id === activeWindowId) {
            className += ` ${style.active}`
          }
          if (!item.closable) {
            className += ` ${style.static}`
          }
          return (
            <div className={className} key={item.id} onClick={() => dispatch(setActiveWindowId(item.id))}>
              {item.isHome ? <HomeFilled className={style['is-home']} /> : null}
              <span className={style['tab-bar__tab__title']}>{item.title}</span>
              {item.closable ? <CloseOutlined className={style['tab-bar__tab__icon']} onClick={(e) => { 
                e.stopPropagation()
                dispatch(delWindow(item.id))
              }} /> : null}
            </div>
          )
        })
      }
      <Popover title='其他页面' trigger='click' content={otherContent} onVisibleChange={v => setVisible(v)}>
        <div className={classNames(style['tab-bar__more-btn'], { [style.active]: visible, [style.hasCurrentPage]: IsHasCurrentPage(hideTabList, activeWindowId) })} onClick={() => setVisible(!visible)}>
          <div className={style['tab-bar__more-btn__inner']}>
            <DownOutlined />
          </div>
        </div>
      </Popover>
    </div>
  )
}

export default Main
